const sessionCache = {
  set (key, value) {
    if (!sessionStorage) {
      return
    }
    if (key != null && value != null) {
      sessionStorage.setItem(key, value)
    }
  },
  get (key) {
    if (!sessionStorage) {
      return null
    }
    if (key == null) {
      return null
    }
    return sessionStorage.getItem(key)
  },
  setJSON (key, jsonValue) {
    if (jsonValue != null) {
      this.set(key, JSON.stringify(jsonValue))
    }
  },
  getJSON (key) {
    const value = this.get(key)
    if (value != null) {
      return JSON.parse(value)
    }
  },
  remove (key) {
    sessionStorage.removeItem(key);
  }
}
const localCache = {
  set (key, value, expires) {
    let storageObj = {
      key: key || '',
      value: value || '',
      expires: expires || 24, // 过期时间，默认24小时
      startTime: (new Date()).getTime() // 时间戳 ms级 毫秒数1661361004580
    }
    if (storageObj.key !== '' && storageObj.value != '') {
      localStorage.setItem(key, JSON.stringify(storageObj))
    }
  },
  get (key) {
    if (key == null || key === '') {
      return null
    } else {
      const result = JSON.parse(localStorage.getItem(key))
      const now = (new Date()).getTime()
      
      if(!result) {
        return null
      } else if (now - result.startTime > result.expires * 60 * 1000) {
				this.remove(key);
				return null;
			} else {
        return result.value
      }
    }
  },
  remove (key) {
    localStorage.removeItem(key);
  }
}
  
export default {
  /**
   * 会话级缓存
   */
  session: sessionCache,
  /**
   * 本地缓存
   */
  local: localCache
}